import { getDangerList } from '../../api/danger'

import { resetObj } from '../../utils/resetObj'

const state = {
  date: '',
  safeSearchDTO: {
    index: 1,
    isShow: 0,
    pageSize: 10,
    projectName: ''
  },
  isShow: 0,
  dangerList: [],
  total: '',
  index: ''
}
const getters = {
  // 项目开始时间
  beginTime (state) {
    if (state.date === ('' || null)) {
      return ''
    } else {
      return state.date[0]
    }
  },
  // 结束时间
  endTime (state) {
    if (state.date === ('' || null)) {
      return ''
    } else {
      return state.date[1]
    }
  },
  // 最终上传的DTO
  searchDTO (state, getters) {
    const DTO = state.safeSearchDTO
    DTO.beginTime = getters.beginTime
    DTO.endTime = getters.endTime
    return DTO
  }
}
const mutations = {
  // 设置隐患列表
  set_dangerList (state, dangerList) {
    state.dangerList = dangerList
  },
  set_total (state, total) {
    state.total = total
  },
  set_isShow (state, isShow) {
    state.safeSearchDTO.isShow = isShow
    state.isShow = isShow
  }
}

const actions = {
  // 获取隐患内容列表
  getList ({ getters, commit }, params) {
    const payload = params ? { ...getters.searchDTO, index: params } : getters.searchDTO
    return new Promise((resolve, reject) => {
      getDangerList(payload).then(res => {
        if (res.data.data) {
          res.data.data.data.forEach(item => {
            item.ifSelect = false
          })
          commit('set_dangerList', res.data.data.data)
          commit('set_total', res.data.data.count)
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 重置查询条件
  async reset ({ state }) {
    state.date = ''
    await resetObj(state.safeSearchDTO)
    state.safeSearchDTO.isShow = state.isShow
    state.safeSearchDTO.index = 1
    state.safeSearchDTO.pageSize = 10
  }
}
export default {
  namespaced: true,
  actions,
  state,
  getters,
  mutations
}
